<template>
  <div class="contract-wrap">
    <u-table
      v-if="contractList.length > 0"
      :data="handleData"
      :border="false"
      :row-height="49"
      class="fb-table"
      element-loading-text="加载中..."
      empty-text="暂无数据"
      header-cell-class-name="order-data-header-cell"
      fit
      hightlight-current-row
      row-class-name="pointer">
      <u-table-column align="left" label="项目名称" min-width="120">
        <template slot-scope="scope">
          <el-tooltip v-if="!scope.row.isOther" :open-delay="800" placement="top" effect="dark">
            <div slot="content" style="max-width: 200px;">{{ scope.row.contractName || '--' }}</div>
            <div class="ellipsisOne" style="cursor:pointer;color:#406eff;" @click="toDetail(scope.row)">{{ scope.row.contractName || '--' }}</div>
          </el-tooltip>
          <ToolTip v-else :content="scope.row.contractName" />
        </template>
      </u-table-column>
      <u-table-column align="left" label="合同编号">
        <template slot-scope="scope">
          <div>
            <ToolTip :content="scope.row.contractCode" />
          </div>
        </template>
      </u-table-column>
      <u-table-column align="left" label="合同日期" min-width="210">
        <template slot-scope="scope">
          <el-tooltip :open-delay="800" placement="top" effect="dark">
            <div slot="content" style="max-width: 220px; white-space: nowrap; padding: 0 10px;">
              <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} {{ handleLimit(scope.row) }} {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
              <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
            </div>
            <div class="line-clamp1">
              <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} {{ handleLimit(scope.row) }} {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
              <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
            </div>
          </el-tooltip>
        </template>
      </u-table-column>
      <u-table-column align="left" label="审批进度" min-width="100">
        <template slot-scope="scope">
          <div v-if="!handleProcess(scope.row)">--</div>
          <div v-else>
            <span :style="{color:handleProcess(scope.row)[0] === handleProcess(scope.row)[1]?'#31CC9C':'#FD8546'}">{{ handleProcess(scope.row)[0] }}</span>/{{ handleProcess(scope.row)[1] }}
          </div>
        </template>
      </u-table-column>
      <u-table-column align="left" label="部门">
        <template slot-scope="scope">
          <div>
            <ToolTip :content="scope.row.department" />
          </div>
        </template>
      </u-table-column>
      <u-table-column align="left" label="合同原件" min-width="120">
        <template slot-scope="scope">
          <span v-if="canScanFileUpload(scope)" class="contract-recycle" @click="contractRecycle(scope)">
            {{ scope.row.recycleAttachmentNum || '上传' }}
            <span v-if="scope.row.recycleAttachmentNum"> 个</span>
          </span>
          <span v-else-if="!isPassed && needPass">
            <span style="color:#FD8546">
              审批通过后展示
            </span>
          </span>
          <span v-else-if="hasRouteAuth('crm:contract:scanFileDownload') || (isPassed && isCreate)" class="contract-recycle">
            <span v-if="scope.row.recycleAttachmentNum" @click="openFileDialog(scope.row)">{{ scope.row.recycleAttachmentNum }}个<i v-if="loading && scope.row.id === currentId" class="el-icon-loading"/></span>
            <span v-else class="contract-recycle disable">上传</span>
          </span>
          <span v-else class="contract-recycle disable">
            {{ scope.row.recycleAttachmentNum || '上传' }}
            <span v-if="scope.row.recycleAttachmentNum"> 个</span>
          </span>
        </template>
      </u-table-column>
      <u-table-column v-if="isEdit" align="left" label="操作" width="110" fixed="right">
        <template slot-scope="scope">
          <div class="delete" @click="delContract(scope.$index)">删除</div>
        </template>
      </u-table-column>
    </u-table>
    <EmptyPlaceholder v-else slot="empty" empty-text="暂无数据" mode="border" style="padding:12px 0 18px 0"/>
    <el-row :justify="showMobilePage ? 'start':'end'" type="flex" class="pagination-area">
      <el-pagination
        v-show="contractList.length > 0"
        :current-page.sync="page"
        :page-size="perPage"
        :small="showMobilePage"
        :total="contractList.length"
        :page-sizes="[10, 20, 50, 100, 250, 500]"
        :layout="showMobilePage ? 'prev, pager, next':'total, prev, pager, next, sizes, jumper'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
    <ContractRecycleDialog ref="contractRecycleDialog" @success="recycleSuccess" />
    <!-- 附件弹窗 -->
    <fileDialog
      ref="fileDialog"
      :file-list="fileList"
    />
  </div>
</template>
<script>

// 组件
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import ContractRecycleDialog from '@/components/contractRecycle/contractRecycleDialog';
// 函数
import { standardFormatNoHour } from '@/filters/date';
import { encryption } from '@/utils';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import fileDialog from './fileDialog';
//  api
import { getFileList } from '@/api/original';

export default {
  components: {
    EmptyPlaceholder,
    ContractRecycleDialog,
    fileDialog
  },
  filters: {
    standardFormatNoHour
  },
  props: {
    id: {
      type: Number,
      default: -1
    },
    contractList: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    isPassed: {
      type: Boolean,
      default: false
    },
    isCreate: {
      type: Boolean,
      default: false
    },
    isCurrentVersion: {// 是否当前版本
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      page: 1,
      perPage: 10,
      fileList: [],
      loading: false,
      currentId: null,
      antiShakeTime: 0 // 防抖时间
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    handleData() {
      return this.contractList.slice((this.page - 1) * this.perPage, this.page * this.perPage);
    },
    needPass() {
      return !this.hasRouteAuth('crm:contract:scanFileDownload') && this.isCreate;
    }
  },
  created() {
  },
  methods: {
    hasRouteAuth,
    // 翻页
    handleSizeChange(val) {
      this.perPage = val;
    },
    handleCurrentChange(val) {
      this.page = val;
    },
    openFileDialog(row) {
      const timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      if (this.isPassed) { // 通过审批获取合同文件
        this.currentId = row.id;// 列表对应位置加小菊花
        const params = {
          id: this.id,
          contractId: row.id// 合同id
        };
        this.getFileList(params);
      } else {
        this.fileList = row.recycleAttachment;
        this.$nextTick(() => {
          this.$refs.fileDialog.openDialog();
        });
      }
    },
    // 获取合同附件
    getFileList(params) {
      this.loading = true;
      getFileList(params).then(res => {
        this.loading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.fileList = res.data;
        this.$nextTick(() => {
          this.$refs.fileDialog.openDialog();
        });
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    // 跳转合同详情
    toDetail(row) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: { id: encryption(row.id) },
        query: {
          processId: encryption(row.processId)
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    contractRecycle(scope) {
      if (!this.canScanFileUpload(scope)) { return; }
      this.$refs['contractRecycleDialog'].dialogVisible = true;
      const data = {
        id: scope.row.id,
        attachment: scope.row.recycleAttachment || [],
        isReview: scope.row.process === 4 && hasRouteAuth('crm:contract:scanFileDownload') || (scope.row.process === 1 && hasRouteAuth('crm:contract:scanFileDownload') && scope.row.setEvents && scope.row.setEvents.includes(1))
      };
      this.$refs['contractRecycleDialog'].initInfo(data);
    },
    recycleSuccess(id) {
      if (this.isEdit) {
        this.$emit('update', id);
      } else {
        this.$emit('updateDetail');
      }
    },
    updateItem(item) {
      const index = this.contractList.findIndex(el => el.id === item.id);
      this.contractList[index] = item;
      this.$set(this.contractList, index, item);
    },
    /*
      是否可以上传
      1、合同进程状态为审批中并且开启合同回收事件和拥有扫描件上传权限
      2、合同进程状态为已完成并且同时拥有扫描件上传权限和扫描件查看/下载权限
    */
    canScanFileUpload(scope) {
      if (!this.isCurrentVersion) { return false; }
      const processStatus = scope.row.process;
      const setEvents = scope.row.setEvents;
      if (processStatus === 1) {
        return setEvents && setEvents.includes(1) && this.hasRouteAuth('crm:contract:scanFileUpload');
      } else if (processStatus === 4) {
        return this.hasRouteAuth('crm:contract:scanFileUpload') && this.hasRouteAuth('crm:contract:scanFileDownload');
      }
      return false;
    },
    /*
      1、有附件没有查看/下载权限
      2、无附件且没有上传权限和查看/下载权限
    */
    handleLimit(row) {
      if (!row.contractEffectEndDate && !row.contractEffectStartDate) {
        return '/';
      }
      return '-';
    },
    handleProcess(row) {
      if (typeof row.reviewProgress !== 'string' || !row.reviewProgress) {
        return false;
      }
      return row.reviewProgress.split('/');
    },
    delContract(index) {
      const idx = index + ((this.page - 1) * this.perPage);
      this.$emit('delContract', idx);
    }
  }
};
</script>
<style lang="scss" scoped>
  .contract-wrap{
    .delete{
      color: #FF4E5F;
    }
    .contract-recycle {
      cursor: pointer;
      color: #406EFF;
      font-weight: bold;
      &.disable {
        cursor: not-allowed;
        color: #999999;
      }
    }
    .pagination-area{
      margin-top: 10px;
    }
  }
</style>
